package com.winsdom.service.customer.impl;

import com.winsdom.entity.customer.CustomerIndividualBasicInfoRequest;
import com.winsdom.mapper.customer.CustomerIndividualBasicInfoMapper;
import com.winsdom.service.customer.CustomerIndividualBasicInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 客户基本信息服务实现类，负责处理客户基本信息的查询和业务逻辑。
 * 该类通过MyBatis Mapper与数据库交互，获取客户基本信息并进行数据组装。
 */
@Service
public class CustomerIndividualBasicInfoServiceImpl implements CustomerIndividualBasicInfoService {

    @Resource
    private CustomerIndividualBasicInfoMapper customerIndividualBasicInfoMapper;

    /**
     * 根据客户ID获取客户基本信息，包括联系人及关联楼盘信息。
     * 该方法通过数据库查询获取客户基本信息、联系人信息及联系人关联的楼盘信息，
     * 并将这些信息整合到一个完整的CustomerBasicInfo对象中返回。
     *
     * @param customerId 客户ID
     * @return 返回封装了客户基本信息的对象，如果没有找到对应记录，返回空的基本信息对象
     */
    @Override
    public CustomerIndividualBasicInfoRequest getCustomerBasicInfo(Long customerId) {
        // 查询数据库获取客户基本信息，结果可能包含多条记录（一个客户可能有多个联系人）
        List<Map<String, Object>> resultList = customerIndividualBasicInfoMapper.selectCustomerBasicInfo(customerId);
        // 初始化返回对象
        CustomerIndividualBasicInfoRequest basicInfo = new CustomerIndividualBasicInfoRequest();

        // 如果查询结果为空，设置空的联系人列表并直接返回
        if (resultList.isEmpty()) {
            basicInfo.setContactInfos(Collections.emptyList());
            return basicInfo;
        }

        // 从第一条记录中获取客户基本信息
        Map<String, Object> baseInfo = resultList.get(0);
        basicInfo.setCustomerId(customerId);
        basicInfo.setCustomerType((Integer) baseInfo.get("customer_type"));
        basicInfo.setCustomerName((String) baseInfo.get("customer_name"));
        basicInfo.setMobilePhone((String) baseInfo.get("mobile_phone"));
        basicInfo.setRegistrationNumber((String) baseInfo.get("registration_number"));
        basicInfo.setBankName((String) baseInfo.get("bank_name"));
        basicInfo.setBankAccount((String) baseInfo.get("bank_account"));
        basicInfo.setEmail((String) baseInfo.get("email"));
        basicInfo.setBusinessLicenseImage((String) baseInfo.get("business_license_image"));
        basicInfo.setBusinessAddressArea((String) baseInfo.get("business_address_area"));
        basicInfo.setBusinessAddressAreaCode((String) baseInfo.get("business_address_area_code"));
        basicInfo.setBusinessDetailedAddress((String) baseInfo.get("business_detailed_address"));

        // 使用Map存储联系人信息，键为contactId，值为ContactInfo对象
        Map<Long, CustomerIndividualBasicInfoRequest.ContactInfo> contactMap = new HashMap<>();

        // 第一遍遍历：收集所有联系人的基本信息（无论是否有关联楼盘）
        for (Map<String, Object> row : resultList) {
            Long contactId = (Long) row.get("contact_id");
            // 如果记录中没有contactId，跳过该记录
            if (contactId == null) {
                continue;
            }

            // 使用computeIfAbsent方法确保每个联系人只被初始化一次
            contactMap.computeIfAbsent(contactId, k -> {
                CustomerIndividualBasicInfoRequest.ContactInfo ci = new CustomerIndividualBasicInfoRequest.ContactInfo();
                ci.setContactName((String) row.get("contact_name"));
                ci.setContactMobile((String) row.get("contact_mobile"));
                ci.setContactEmail((String) row.get("contact_email"));
                ci.setReceiveProperties(new ArrayList<>()); // 初始化接收楼盘列表
                return ci;
            });
        }

        // 第二遍遍历：处理联系人与楼盘的关联关系
        for (Map<String, Object> row : resultList) {
            Long contactId = (Long) row.get("contact_id");
            if (contactId == null) {
                continue;
            }

            CustomerIndividualBasicInfoRequest.ContactInfo contactInfo = contactMap.get(contactId);
            String propertyName = (String) row.get("property_name");
            // 如果记录中包含楼盘名称，将其添加到对应联系人的接收楼盘列表中
            if (propertyName != null) {
                contactInfo.getReceiveProperties().add(propertyName);
            }
        }

        // 处理没有联系人信息的情况，使用客户基本信息中的联系人字段
        if (contactMap.isEmpty()) {
            CustomerIndividualBasicInfoRequest.ContactInfo contactInfo = new CustomerIndividualBasicInfoRequest.ContactInfo();
            contactInfo.setContactName((String) baseInfo.get("contact_name"));
            contactInfo.setContactMobile((String) baseInfo.get("contact_mobile"));
            contactInfo.setContactEmail((String) baseInfo.get("contact_email"));
            contactInfo.setReceiveProperties(Collections.emptyList());
            basicInfo.setContactInfos(Collections.singletonList(contactInfo));
        } else {
            // 将Map中的联系人信息转换为列表设置到基本信息对象中
            basicInfo.setContactInfos(new ArrayList<>(contactMap.values()));
        }

        return basicInfo;
    }
}